package com.ruoyi.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class CreateImageUtils {

    public static String generateQRCodeBase64(String data, int width, int height)
        throws WriterException, IllegalArgumentException {
        // 输入验证‌:ml-citation{ref="1" data="citationList"}
        // 生成二维码矩阵‌:ml-citation{ref="7" data="citationList"}
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix matrix = writer.encode(data, BarcodeFormat.QR_CODE, width, height, hints);

        // 转换为内存图片‌:ml-citation{ref="7" data="citationList"}
        BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);

        // 转为Base64‌:ml-citation{ref="5,7" data="citationList"}
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "PNG", baos);
            byte[] bytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            throw new WriterException("Base64转换异常: " + e.getMessage());
        }
    }
}
